import NodeId
#from NodeIdType import PTR
from NodeIdType import NodeIdType
import NodeIdType
from base import BitsLong
from base.exception.TDBException import TDBException
import DoubleNode62

# class NodeIdFactory:
#     counter = 0xb0
#     def __init__(self):
#         counter = 0
#         pass

def create(type, v1, v2):
    if (isSpecial(type)):
        if (NodeId.equals(NodeId.NodeDoesNotExist, v1, v2)):
            return NodeId.NodeDoesNotExist;
        if (NodeId.equals(NodeId.NodeIdAny, v1, v2)):
            return NodeId.NodeIdAny;
        if (NodeId.equals(NodeId.NodeIdDefined, v1, v2)):
            return NodeId.NodeIdDefined;
        if (NodeId.equals(NodeId.NodeIdDefined, v1, v2)):
            return NodeId.NodeIdDefined;
        if (NodeId.equals(NodeId.NodeIdUndefined, v1, v2)):
            return NodeId.NodeIdUndefined;

    return createNew(type, v1, v2)

def isSpecial(type):
    pass

def createValue(nodeIdType, value):
    return createNew(nodeIdType, 0, value)

def createNew(type, v1, v2):
    # Create general NodeId form.
    return NodeId.createRaw(type, v1, v2)

# return NodeId
def createPtr(lowValue):
    return createNew(NodeIdType.PTR, 0, lowValue)

# ---- Create from binary.

# return NodeId
def createPtrLong(highValue, lowValue):
    return create(NodeIdType.PTR, highValue, lowValue)

# parameter long
# return NodeId
def create64(value2):
    if not BitsLong.isSet(value2, 63):
        return createPtr(value2)
    # Inline.
    v2 = value2
    if not BitsLong.isSet(v2, 62):
        # XSD_DOUBLE
        v2 = DoubleNode62.removeType(v2)
        return NodeId.createRaw(NodeIdType.XSD_DOUBLE, v2)

    t = BitsLong.unpack(v2, 56, 63)   # 7 bits
    v2 = BitsLong.clear2(v2, 56, 64)
    #NodeIdType
    type = NodeIdType.intToEnum(t)
    if (type == NodeIdType.SPECIAL):
        raise TDBException(f"Attempt to create a special from a long: 0x%016", v2)
    return NodeId.createRaw(type, v2)


